package io.terminus.paas.profiler.restful

import io.terminus.paas.profiler.common.BaseController
import io.terminus.paas.profiler.model.Consumer
import io.terminus.paas.profiler.model.Permission
import io.terminus.paas.profiler.model.Provider
import io.terminus.paas.profiler.model.ServiceModel
import io.terminus.paas.profiler.service.ConsumerService
import io.terminus.paas.profiler.service.PermissionService
import io.terminus.paas.profiler.service.ProviderService
import io.terminus.paas.profiler.service.ServiceService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController

/**
 * Created by gengrong on 16/5/16.
 */
@RestController
@RequestMapping("/api/services")
class Services @Autowired constructor(
        private val permissionService: PermissionService,
        private val providerService: ProviderService,
        private val consumerService: ConsumerService,
        private val serviceService: ServiceService
) : BaseController() {

    @RequestMapping(method = arrayOf(RequestMethod.GET))
    fun serviceList(): List<ServiceModel> = serviceService.listAll(getRegistryAddress())

    @RequestMapping("/{serviceId:.*}", method = arrayOf(RequestMethod.GET))
    fun desc(@PathVariable serviceId: String): ServiceModel {
        return serviceService.getDetailByServiceId(getRegistryAddress(), serviceId)
    }

    @RequestMapping("/{serviceId:.*}/consumers", method = arrayOf(RequestMethod.GET))
    fun consumers(@PathVariable serviceId: String): List<Provider> {
        return providerService.findProviderByServiceId(getRegistryAddress(), serviceId)
    }

    @RequestMapping("/{serviceId:.*}/providers", method = arrayOf(RequestMethod.GET))
    fun providers(@PathVariable serviceId: String): List<Consumer> {
        return consumerService.findConsumerByServiceId(getRegistryAddress(), serviceId)
    }

    @RequestMapping("/{serviceId:.*}/permissions", method = arrayOf(RequestMethod.GET))
    fun permissions(@PathVariable serviceId: String): Permission {
        return permissionService.findByServiceId(getRegistryAddress(), serviceId)
    }

    @RequestMapping("/{serviceId:.*}/permissions", method = arrayOf(RequestMethod.POST))
    fun updatePermission(@PathVariable serviceId: String, allow: String, denial: String) {
        permissionService.savePermission(getRegistryAddress(), serviceId, allow, denial);
    }

    @RequestMapping("/{serviceId:.*}/tags", method = arrayOf(RequestMethod.POST))
    fun updateTag(@PathVariable serviceId: String, tags: String?) {
        serviceService.updateTag(getRegistryAddress(), serviceId, tags);
    }
}